package com.study.crypto.basic.general.spring.interceptor;

import com.study.crypto.basic.utils.EssPdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Songjin
 * @since 2022-11-01 14:10
 */
@Slf4j
public class TraceIdInterceptor implements HandlerInterceptor {

    public static final String TRACE_ID = "__trace_id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String headerTraceId = request.getHeader(TRACE_ID);
        String requestTraceId = WebUtils.findParameterValue(request, TRACE_ID);
        String traceId = StringUtils.defaultIfBlank(headerTraceId, StringUtils.defaultIfBlank(requestTraceId, EssPdfUtil.genRandomUuid()));
        try {
            MDC.put(TRACE_ID, traceId);
            request.setAttribute(TRACE_ID, traceId);
        } catch (Exception e) {
            log.error("[mdc_error]", e);
        }
        if (!HttpMethod.HEAD.matches(request.getMethod())) {
            LoggerFactory.getLogger(getClass()).info("__trace_id :{}", traceId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            MDC.remove(TRACE_ID);
        } catch (Exception e) {
            log.error("[mdc_error]", e);
        }
    }

}
